package com.yilin.tms.capital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yilin.tms.capital.mapper.StatisticsMapper;
import com.yilin.tms.capital.mapper.TradeRecordMapper;
import com.yilin.tms.capital.service.IStatisticsService;
import com.yilin.tms.core.entity.capital.TradeRecord;
import com.yilin.tms.core.entity.data.statistics.TradeRecordStatistics;
import com.yilin.tms.core.entity.data.statistics.capital.CapitalStatistics;
import com.yilin.tms.core.entity.user.account.Account;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Map;

@Service
@Transactional(rollbackOn = Exception.class)
public class StatisticsService implements IStatisticsService {

    @Resource
    TradeRecordMapper tradeRecordMapper;

    @Resource
    StatisticsMapper statisticsMapper;

    @Override
    public TradeRecordStatistics getTradeRecordStatistics() {
        TradeRecordStatistics statistics = new TradeRecordStatistics();
        statistics.setPayment(Math.toIntExact(tradeRecordMapper.selectCount(new QueryWrapper<TradeRecord>().eq("trade_type", TradeRecord.TradeType.payment).eq("trade_status", TradeRecord.TradeStatus.create))));
        statistics.setRefund(Math.toIntExact(tradeRecordMapper.selectCount(new QueryWrapper<TradeRecord>().eq("trade_type", TradeRecord.TradeType.refund).eq("trade_status", TradeRecord.TradeStatus.create))));
        statistics.setSettlement(Math.toIntExact(tradeRecordMapper.selectCount(new QueryWrapper<TradeRecord>().eq("trade_type", TradeRecord.TradeType.settlement).eq("trade_status", TradeRecord.TradeStatus.create))));
        if (statistics.getPayment() == 0 && statistics.getSettlement() == 0 && statistics.getRefund() == 0) {
            statistics.setAllEmpty(true);
        }
        return statistics;
    }

    @Override
    public Map<String, Object> getCapitalFundStatistics(Account loginUser) {
        return statisticsMapper.getCapitalFundStatistics(loginUser);
    }

    /**
     * 资金统计
     */
    @Override
    public CapitalStatistics getCapitalStatistics(Account loginUser) {
        //获取资金收入和支出的总计、年、月、日金额
        CapitalStatistics capitalStatistics = statisticsMapper.getCapitalCount(loginUser);
        //资金收入趋势折线图
        capitalStatistics.setCapitalIncomeTrends(statisticsMapper.getCapitalIncomeTrends(loginUser));
        //资金支出趋势折线图
        capitalStatistics.setCapitalExpenditureTrends(statisticsMapper.getCapitalExpenditureTrends(loginUser));
        return capitalStatistics;
    }
}
